package com.hongkuncheng.cms.controller.admin;

import java.util.List;
import java.util.ArrayList;

import org.hibernate.LockMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Controller;
import com.hongkuncheng.cms.controller.BaseController;
import com.hongkuncheng.cms.helper.DataHelper;
import com.hongkuncheng.cms.helper.PageHelper;
import com.hongkuncheng.cms.model.Columns;
import com.hongkuncheng.cms.model.Gather;
import com.hongkuncheng.cms.model.GatherReColumns;
import com.hongkuncheng.cms.model.Zhuanti;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 采集项目管理
 *
 * @author 洪坤成
 */
@Controller
@Transactional
@RequestMapping("admin/gatherproject")
public class AgatherprojectController extends BaseController {

    // 采集项目列表
    @RequestMapping
    public String index() {
        List<Gather> gathers = factorySession.createCriteria(Gather.class).list();
        request.setAttribute("gathers", gathers);
        return view();
    }

    // 采集项目编辑
    @RequestMapping("edit")
    public String edit() {
        int gatherId = request.getParameter("gatherid") == null ? 0 :
                Integer.parseInt(request.getParameter("gatherid"));
        Gather gather = gatherId == 0 ? new Gather() : factorySession.get(Gather.class, gatherId);
        request.setAttribute("gather", gather);
        List<Integer> columnsIds = new ArrayList<Integer>();
        if (gatherId > 0)
            for (GatherReColumns grc : gather.getGatherReColumnses())
                columnsIds.add(grc.getColumns().getId());
        request.setAttribute("columnsids", columnsIds);
        // 栏目集合
        List<Columns> columnses = new ArrayList<Columns>();
        List<Columns> columnsForZhuanties = new ArrayList<Columns>();
        List<Zhuanti> zhuantis = new ArrayList<Zhuanti>();
        List<Integer> zhuantiIds = new ArrayList<Integer>();
        List<Columns> columns1es = factorySession.createCriteria(Columns.class)
                .add(Restrictions.eq("parentId", 0))
                .addOrder(Order.asc("sort")).list();
        for (Columns columns1 : columns1es) {
            List<Columns> columns2Temp = factorySession.createCriteria(Columns.class)
                    .add(Restrictions.eq("columnsType.id", 1))
                    .add(Restrictions.eq("parentId", columns1.getId()))
                    .addOrder(Order.asc("sort")).list();
            if (columns1.getColumnsType().getId() == 1 || columns2Temp.size() > 0)
                columnses.add(columns1);
            if (columns2Temp.size() > 0)
                for (Columns columns2 : columns2Temp) columnses.add(columns2);
            if (columns1.getColumnsType().getId() == 6) {
                if (!zhuantiIds.contains(columns1.getZhuanti().getId())) {
                    zhuantis.add(columns1.getZhuanti());
                    zhuantiIds.add(columns1.getZhuanti().getId());
                }
                columnsForZhuanties.add(columns1);
            }
        }
        request.setAttribute("columnses", columnses);
        request.setAttribute("zhuantis", zhuantis);
        request.setAttribute("columnsForZhuanties", columnsForZhuanties);
        return view();
    }

    // 采集项目编辑处理
    @RequestMapping("editdo")
    @ResponseBody
    public void editdo() {
        checkAdminPermission("yunwei_systemsetup_gatherproject");
        int gatherId = Integer.parseInt(request.getParameter("gatherid"));
        Gather gather = gatherId == 0 ? new Gather() :
                factorySession.get(Gather.class, gatherId, LockMode.PESSIMISTIC_WRITE);
        gather.setName(request.getParameter("name"));
        gather.setTargeturl(request.getParameter("targeturl"));
        gather.setEncode(request.getParameter("encode"));
        gather.setRegexlist(request.getParameter("regexlist"));
        gather.setRegexlinkurl(request.getParameter("regexlinkurl"));
        gather.setRegexdetail(request.getParameter("regexdetail"));
        gather.setOutlink(Boolean.parseBoolean(request.getParameter("outlink")));
        gather.setAutogather(request.getParameter("autogather") != null);
        List<Integer> columnsIds = DataHelper.convertToIntegerList(request.getParameterValues("columnsids"));
        if (gatherId == 0) {
            factorySession.save(gather);
        } else {
            if (gather.getGatherReColumnses().size() > 0) {
                // 删除原来的映射关系
                List<Object> grcs = new ArrayList<>();
                for (GatherReColumns grc : gather.getGatherReColumnses()) {
                    if (!columnsIds.contains(grc.getColumns().getId())) grcs.add(grc);
                    else columnsIds.remove(Integer.valueOf(grc.getColumns().getId()));
                }
                factorySession.delete(grcs);
            }
        }
        if (columnsIds.size() > 0) {
            // 创建新的映射关系
            List<Columns> columnses = factorySession.createCriteria(Columns.class)
                    .add(Restrictions.in("id", columnsIds)).list();
            for (Columns columns : columnses) {
                GatherReColumns grc = new GatherReColumns();
                grc.setGather(gather);
                grc.setColumns(columns);
                factorySession.save(grc);
            }
        }
        recordLog((gatherId == 0 ? "新增" : "修改") + "采集项目《" + gather.getName() + "》");
        PageHelper.alertAndRedirect("保存成功", "./");
    }

    // 采集项目删除
    @RequestMapping("delete")
    @ResponseBody
    public void delete() {
        checkAdminPermission("yunwei_systemsetup_gatherproject");
        int gatherId = Integer.parseInt(request.getParameter("gatherid"));
        Gather gather = factorySession.get(Gather.class, gatherId, LockMode.PESSIMISTIC_WRITE);
        factorySession.delete(gather);
        recordLog("删除采集项目《" + gather.getName() + "》");
        PageHelper.alertAndRedirect("保存成功", "./");
    }

}
